<template>
  <div class="app-container">
    <div class="filter-container">
      <!--      <el-select v-model="listQuery.navi_id" filterable placeholder="请选择" class="filter-item" @change="getList"-->
      <!--                 clearable style="margin-left:5px;"-->
      <!--      >-->
      <!--        <el-option-->
      <!--          v-for="item in selfList"-->
      <!--          :key="item.id"-->
      <!--          :label="item.label"-->
      <!--          :value="item.id"-->
      <!--        >-->
      <!--        </el-option>-->
      <!--      </el-select>-->
<!--      <el-input-->
<!--        class="filter-item"-->
<!--        placeholder="输入关键字进行过滤"-->
<!--        v-model="listQuery.keyword"-->
<!--        style="width: 30%;"-->
<!--      >-->
<!--      </el-input>-->
<!--      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="getList"-->
<!--                 style="margin-left: 10px"-->
<!--      >-->
<!--        搜索-->
<!--      </el-button>-->
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit"
                 @click="handleCreate"
      >
        添加
      </el-button>
    </div>
    <el-divider><font color="#ccc"> 图片推荐尺寸比例为(宽:580px,高:280px )</font></el-divider>
    <el-row :gutter="12"  v-if="total>0">
      <el-col :xs="24" :sm="24" :lg="6" v-for="item in list">
        <el-card style="margin-top:1px;height: 320px">
          <center>
            <el-tooltip content="点击放大" placement="right" effect="light">
              <el-image fit="contain" :src="item.thumb" style="height:200px" @click="showBanner(item.image)"></el-image>
            </el-tooltip>

           <el-divider>
             <el-button type="primary" size="mini" icon="el-icon-edit" circle @click="handleUpdate(item)">
             </el-button>
             <el-button size="mini" type="danger" icon="el-icon-delete" circle @click="handleDelete(item)">
             </el-button>
<!--             <font color="#ccc" style="font-size:14px" :show-overflow-tooltip='true'>{{item.title| ttlipsis}}</font>-->
           </el-divider>
          </center>
        </el-card>
      </el-col>
    </el-row>
    <el-empty v-else description="暂无内容"></el-empty>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="40%">
      <el-form ref="dataForm" :rules="rules" :model="temp"  label-width="80px" >
        <el-form-item prop="title">
          <MDinput v-model="temp.url" :maxlength="200" name="title" required>
            外链
          </MDinput>
        </el-form-item>
        <el-form-item label="图片" prop="image">
          <el-upload
            class="avatar-uploader"
            action="/api/upload/base_image"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <el-image v-if="imageUrl" :src="imageUrl+'?rondom='+ Math.ceil(Math.random()*5)" class="avatar" width="100%" fit="contain"></el-image>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="排序" prop="price">
          <el-input v-model="temp.sort" type="number"/>
        </el-form-item>
<!--        <el-form-item prop="content" label="内容">-->
<!--          <vue-ueditor-wrap v-model="temp.content" :config="myConfig"/>-->
<!--        </el-form-item>-->
      </el-form>
      <center>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="createData()">
            确认
          </el-button>
        </div>
      </center>
    </el-dialog>
    <el-dialog :visible.sync="dialogBannerVisible" width="80%">
      <center>
        <el-image  fit="contain" :src="showBannerUrl" width="100%"></el-image>
      </center>
    </el-dialog>
  </div>
</template>

<script>
import { getList,create,del} from '@/api/main_banner'
import Pagination from '@/components/Pagination'
import MDinput from '@/components/MDinput'
import Tinymce from '@/components/Tinymce'
import VueUeditorWrap from 'vue-ueditor-wrap'
export default {
  name: 'BannerMain',
  components:{ Pagination,MDinput,Tinymce,VueUeditorWrap},
  data() {
    return {
      myConfig: {
        autoHeightEnabled: false,
        initialFrameHeight: 500,
        initialFrameWidth: '100%',
        zIndex:99999,
        serverUrl: '/admin/UEditor/php/controller.php',
        UEDITOR_HOME_URL: '/admin/UEditor/'//build 路径
        // UEDITOR_HOME_URL: '/UEditor/' //调试路径
      },
      selfList:[],
      content: '',
      imageUrl: '',
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20
      },
      dialogFormVisible: false,
      dialogBannerVisible:false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      typeList:[
        {
          'type':'',
          'name':'',
        }
      ],
      showBannerUrl:'',
      temp: {
        id: undefined,
        image:'',
        thumb:'',
        sort:'',
        url:''
      },
      rules: {
        image: [{ required: true, message: '请上传图片', trigger: 'blur' }],
        url: [{ required: true, message: '外链不能为空', trigger: 'blur' }]
      },

    }
  },
  filters: {
    ellipsis(value) {
      if (!value) return ''
      if (value.length > 100) {
        return value.slice(0, 100) + '...'
      }
      return value
    },
    ttlipsis(value) {
      if (!value) return ''
      if (value.length > 14) {
        return value.slice(0, 14) + '...'
      }
      return value
    }
  },
  watch: {
    imageUrl: {
      deep: true,
      handler(val) {
      }
    }
  },
  computed: {
    contentShortLength() {
      return this.temp.desc.length
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getUrlKey(name){//获取url 参数
      return decodeURIComponent(
        (new RegExp('[?|&]'+name+'='+'([^&;]+?)(&|#|;|$)').exec(location.href)||[,""])[1].replace(/\+/g,'%20'))||null;
    },
    getList() {
      this.listLoading = true
      getList(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.total
        // Just to simulate the time of the request
        this.listLoading = false
      })
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        image:'',
        thumb:'',
        sort:'',
        url:''
      }
      this.imageUrl=''
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if(!this.temp.image || !this.temp.thumb){
            this.$message.error('请先上传图片')
            return ''
          }
          create(this.temp).then(response => {
            if(response.code == 200){
              this.dialogFormVisible = false
              this.$notify({
                message: response.msg,
                type: 'success',
                duration: 2000
              })
              this.getList()
            }else{
              this.$notify.error({
                message: response.msg,
                duration: 2000
              })
            }
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.imageUrl =this.temp.thumb
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if(!this.temp.image || !this.temp.thumb){
            this.$message.error('请先上传图片')
            return ''
          }
          const tempData = Object.assign({}, this.temp)
          update(tempData).then(response => {
            if(response.code == 200){
              this.dialogFormVisible = false
              this.$notify({
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            }else{
              this.$notify.error({
                message: response.msg,
                duration: 2000
              })
            }
          })
        }
      })
    },

    handleAvatarSuccess(res, file) {
      if(res.code == 200){
        this.imageUrl = res.data.thumb
        this.temp.image = res.data.url
        this.temp.thumb = res.data.thumb
        this.$notify({
          title: '消息',
          type:'success',    handleAvatarSuccess(res, file) {
            if(res.code == 200){
              this.imageUrl = res.data.thumb
              this.temp.image = res.data.url
              this.temp.thumb = res.data.thumb
              this.$notify({
                title: '消息',
                type:'success',
                message:'上传成功',
                duration: 2000
              });
            }else{
              this.$notify({
                title: '消息',
                type:'error',
                message:'上传失败',
                duration: 2000
              });
            }
            // this.imageUrl = URL.createObjectURL(file.raw);
          },
          beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isPNG = file.type === 'image/png';
            const isLt10M = file.size / 1024 / 1024 < 10;
            if (!isJPG && !isPNG) {
              this.$message.error('上传图片只能是 JPG/PNG 格式!');
            }
            if (!isLt10M) {
              this.$message.error('上传图片大小不能超过 10MB!');
            }
            return isLt10M
            //  return isJPG && isLt2M;
          },
          message:'上传成功',
          duration: 2000
        });
      }else{
        this.$notify({
          title: '消息',
          type:'error',
          message:'上传失败',
          duration: 2000
        });
      }
      // this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isJPG && !isPNG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!');
      }
      if (!isLt10M) {
        this.$message.error('上传图片大小不能超过 10MB!');
      }
      return isLt10M
      //  return isJPG && isLt2M;
    },
    handleDelete(row, index) {
      this.$confirm(
        '确定要删除该条数据吗？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(()=>{
        del(row.id).then(response => {
          if(response.code == 200){
            this.list.splice(index, 1)
            this.$notify({
              message: response.msg,
              type: 'success',
              duration: 2000
            })
          }else {
            this.$notify.error({
              message: response.msg,
              duration: 2000
            })
          }
        })
      }).catch(()=>{

      })
    },
    showBanner(url){
      this.showBannerUrl =url
      this.dialogBannerVisible = true
    }
  }
}
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.el-tooltip__popper{
  max-width:60%;
}
.el-tooltip__popper,.el-tooltip__popper.is-dark{
  background:rgb(48, 65, 86) !important;
  color: #fff !important;
  line-height: 24px;
}
</style>
<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.article-textarea ::v-deep {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}
</style>
